#@revision $Revision$ 
#@author Jorge Niedbalski R. <jnr@niedbalski.org>

from   Exception import NotFoundException
import json
import os

class Singleton(type):
    def _init_(cls, name, bases, dict):
        super(Singleton, cls)._init_(name, bases, dict)
        cls.instance = None 

    def _call_(cls,*args,**kw):
        if cls.instance is None:
            cls.instance = super(Singleton, cls)._call_(*args, **kw)
            return cls.instance

class    SCQueueConfig:

    _metaclass_ = Singleton

    DEBUG = True
    DEFAULT_THREADS    = 4
    DEFAULT_WAIT_TIME  = 3
    DEFAULT_QUEUE_NAME = 'default'
    DEFAULT_DIR_MASK   = 0755
    TASK_TIMEOUT       = False
    TASK_DONE          = True

    def   __init__(self, filename):
        if self._checkFilename(filename):
            self._parse()
            self._initDirectories()
    
    def   _checkFilename(self, filename):
        if not ( os.path.exists(filename) and os.access(filename, os.R_OK) ):
            raise Exception("Cannot read configuration file : %s" % (filename))
        self._config_filename = filename
        return True

    def   _parse(self):
        fd    = open(self._config_filename, "rb")

        if not fd:
            raise Exception("Cannot open configuration file")

        file_size = os.path.getsize(self._config_filename)
        readed      = fd.read(file_size)

        if not readed:
            raise Exception("Cannot read configuration file")

        decoded = json.JSONDecoder().decode(readed)

        if not decoded:
            raise Exception("Cannot parse decoded configuration")

        if not decoded['server'].has_key('queues_path'):
            raise Exception("Default path for queues is not defined")

        self._initQueuesPath(decoded['server']['queues_path'])
        self._config = decoded

    def   _initDirectories(self):
        queues = self.getQueues()
        
        for queue in queues:
            directory = "%s%s" % (self.getQueuesPath(), queue)
            if os.path.exists(directory):
                if not os.access(directory, os.O_RDWR):
                    raise Exception("Cannot write to queue directory : %s", directory)
            else:
                os.mkdir(directory, self.DEFAULT_DIR_MASK)

    def   _initQueuesPath(self, path):
        if not ( os.path.exists(path) ):
            if not os.access(path, os.O_RDWR):
                raise Exception("Invalid path for queues : %s" % ( path))
            os.mkdir(path, self.DEFAULT_DIR_MASK)
        else:
            if not os.access(path, os.O_RDWR):
                raise Exception("Invalid path for queues : %s" % ( path))
        
    def   get(self):
        return self._config 

    def   getFilename(self):
        return self._config_filename

    def   getQueuesPath(self):
        return self._config['server']['queues_path']

    def   getQueues(self):
        return self._config['queues']

    def   getQueue(self, name):
        if not self._config['queues'].has_key(name._str_()):
            raise NotFoundException("Not found queue declaration for %s" %  (name))
        return self._config['queues'][name._str_()]

    def   getServer(self):
        return self._config['server']
    
    def   getServerListener(self):
        return self._config['server']['listener']

    def   getWorkers(self):
        return int(self._config['server']['worker']['start'])


Config   = SCQueueConfig("./config/main.json")
